package com.wxh.multithread;

/**
 * @ClassName: DeadLock
 * @Description: 死锁：多个线程互相抱着对方的资源，然后形成僵持
 * @Author wxh
 * @Date: 2022/2/17 10:27
 * @Version V1.0.0
 * @Since 1.8
 */
public class DeadLock {

    /**
     *  死锁产生条件：互斥条件、请求与保持条件、不剥夺条件、循环等待条件
     * @param args
     */
    public static void main(String[] args) {
        Makeup girl1 = new Makeup(0, "灰姑娘");
        Makeup girl2 = new Makeup(1, "白雪公主");

        girl1.start();
        girl2.start();
    }
}

/**
 * 口红
 */
class Lipstick {

}

/**
 *  镜子
 */
class Mirror {

}

/**
 *  化妆
 */
class Makeup extends Thread {

    // 需要资源只要一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    /**
     * 选择
     */
    int choice;
    /**
     * 使用化妆的人
     */
    String girlNmae;

    Makeup(int choice, String girlNmae){
        this.choice = choice;
        this.girlNmae = girlNmae;
    }

    @Override
    public void run() {
       // 化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 化妆，互相持有对方的锁，就是需要拿到对方的资源
     */
    private void makeup() throws InterruptedException {
        if(choice == 0){
            // 获得口红的锁
            synchronized (lipstick){
                System.out.println(this.girlNmae + "获得口红的锁");
                Thread.sleep(1000);
            }

            // 一秒钟后，获得镜子的锁
            synchronized (mirror){
                System.out.println(this.girlNmae + "获得镜子的锁");
            }
        } else {
            // 获得镜子的锁
            synchronized (mirror){
                System.out.println(this.girlNmae + "获得镜子的锁");
                Thread.sleep(2000);
            }

            // 两秒钟后，获得口红的锁
            synchronized (lipstick){
                System.out.println(this.girlNmae + "获得口红的锁");
            }
        }
    }


}
